package jnpf.zc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zc.entity.ZcglCustomerBusinessEntity;
import jnpf.zc.entity.ZcglCustomerEntity;
import jnpf.zc.entity.ZcglCustomerUserEntity;
import jnpf.zc.mapper.ZcglCustomerMapper;
import jnpf.zc.model.zcglcustomer.ZcglCustomerForm;
import jnpf.zc.model.zcglcustomer.ZcglCustomerPagination;
import jnpf.zc.service.ZcglCustomerBusinessService;
import jnpf.zc.service.ZcglCustomerService;
import jnpf.zc.service.ZcglCustomerUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * 客户库
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-12-28
 */
@Service
public class ZcglCustomerServiceImpl extends ServiceImpl<ZcglCustomerMapper, ZcglCustomerEntity> implements ZcglCustomerService {


        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;

    @Autowired
	private ZcglCustomerBusinessService zcglCustomerBusinessService;
    @Autowired
	private ZcglCustomerUserService zcglCustomerUserService;




    @Override
    public List<ZcglCustomerEntity> getList(ZcglCustomerPagination zcglCustomerPagination){
        return getTypeList(zcglCustomerPagination,zcglCustomerPagination.getDataType());
    }
    @Override
    public List<ZcglCustomerEntity> getTypeList(ZcglCustomerPagination zcglCustomerPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int zcglCustomerNum =0;
        QueryWrapper<ZcglCustomerEntity> zcglCustomerQueryWrapper=new QueryWrapper<>();
		int zcglCustomerUserNum =0;
        QueryWrapper<ZcglCustomerUserEntity> zcglCustomerUserQueryWrapper=new QueryWrapper<>();
		int zcglCustomerBusinessNum =0;
        QueryWrapper<ZcglCustomerBusinessEntity> zcglCustomerBusinessQueryWrapper=new QueryWrapper<>();
            long zcglCustomerUsercount = zcglCustomerUserService.count();
            long zcglCustomerBusinesscount = zcglCustomerBusinessService.count();
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(zcglCustomerPagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglCustomerPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();
        int zcglCustomerNum1 = 0;
        QueryWrapper<ZcglCustomerEntity> zcglCustomerSuperWrapper = new QueryWrapper<>();
        zcglCustomerNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglCustomerSuperWrapper,superQueryList,matchLogic,"zcglCustomer")
        ,new ZcglCustomerEntity(),zcglCustomerNum1);
            if (zcglCustomerNum1>0){
            List<String> zcglCustomerList =this.list(zcglCustomerSuperWrapper).stream().map(ZcglCustomerEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(zcglCustomerList);
            intersectionSuperList.add(zcglCustomerList);
            }
        int zcglCustomerUserNum1 = 0;
        QueryWrapper<ZcglCustomerUserEntity> zcglCustomerUserSuperWrapper = new QueryWrapper<>();
        zcglCustomerUserNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglCustomerUserSuperWrapper,superQueryList,matchLogic,"zcglCustomerUser")
        ,new ZcglCustomerUserEntity(),zcglCustomerUserNum1);
            if (zcglCustomerUserNum1>0 && zcglCustomerUsercount>0){
            List<String> zcglCustomerUserList =zcglCustomerUserService.list(zcglCustomerUserSuperWrapper).stream().map(ZcglCustomerUserEntity::getParentid).collect(Collectors.toList());
            allSuperList.addAll(zcglCustomerUserList);
            intersectionSuperList.add(zcglCustomerUserList);
            }
        int zcglCustomerBusinessNum1 = 0;
        QueryWrapper<ZcglCustomerBusinessEntity> zcglCustomerBusinessSuperWrapper = new QueryWrapper<>();
        zcglCustomerBusinessNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglCustomerBusinessSuperWrapper,superQueryList,matchLogic,"zcglCustomerBusiness")
        ,new ZcglCustomerBusinessEntity(),zcglCustomerBusinessNum1);
            if (zcglCustomerBusinessNum1>0 && zcglCustomerBusinesscount>0){
            List<String> zcglCustomerBusinessList =zcglCustomerBusinessService.list(zcglCustomerBusinessSuperWrapper).stream().map(ZcglCustomerBusinessEntity::getParentid).collect(Collectors.toList());
            allSuperList.addAll(zcglCustomerBusinessList);
            intersectionSuperList.add(zcglCustomerBusinessList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
				Object zcglCustomerObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCustomerQueryWrapper,zcglCustomerPagination.getMenuId(),"zcgl_customer"));
            if (ObjectUtil.isEmpty(zcglCustomerObj)){
                return new ArrayList<>();
            } else {
                zcglCustomerQueryWrapper = (QueryWrapper<ZcglCustomerEntity>)zcglCustomerObj;
                zcglCustomerNum++;
            }
				Object zcglCustomerUserObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCustomerUserQueryWrapper,zcglCustomerPagination.getMenuId(),"zcgl_customer_user"));
            if (ObjectUtil.isEmpty(zcglCustomerUserObj)){
                return new ArrayList<>();
            } else {
                zcglCustomerUserQueryWrapper = (QueryWrapper<ZcglCustomerUserEntity>)zcglCustomerUserObj;
                zcglCustomerUserNum++;
            }
				Object zcglCustomerBusinessObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCustomerBusinessQueryWrapper,zcglCustomerPagination.getMenuId(),"zcgl_customer_business"));
            if (ObjectUtil.isEmpty(zcglCustomerBusinessObj)){
                return new ArrayList<>();
            } else {
                zcglCustomerBusinessQueryWrapper = (QueryWrapper<ZcglCustomerBusinessEntity>)zcglCustomerBusinessObj;
                zcglCustomerBusinessNum++;
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object zcglCustomerObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCustomerQueryWrapper,zcglCustomerPagination.getMenuId(),"zcglCustomer"));
            if (ObjectUtil.isEmpty(zcglCustomerObj)){
                return new ArrayList<>();
            } else {
            zcglCustomerQueryWrapper = (QueryWrapper<ZcglCustomerEntity>)zcglCustomerObj;
            zcglCustomerNum++;
			}


			Object zcglCustomerUserObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCustomerUserQueryWrapper,zcglCustomerPagination.getMenuId(),"zcglCustomerUser"));
            if (ObjectUtil.isEmpty(zcglCustomerUserObj)){
                return new ArrayList<>();
            } else {
            zcglCustomerUserQueryWrapper = (QueryWrapper<ZcglCustomerUserEntity>)zcglCustomerUserObj;
            zcglCustomerUserNum++;
			}


			Object zcglCustomerBusinessObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglCustomerBusinessQueryWrapper,zcglCustomerPagination.getMenuId(),"zcglCustomerBusiness"));
            if (ObjectUtil.isEmpty(zcglCustomerBusinessObj)){
                return new ArrayList<>();
            } else {
            zcglCustomerBusinessQueryWrapper = (QueryWrapper<ZcglCustomerBusinessEntity>)zcglCustomerBusinessObj;
            zcglCustomerBusinessNum++;
			}


		}
    }
        if(isPc){
			if(ObjectUtil.isNotEmpty(zcglCustomerPagination.getProject())){
            zcglCustomerNum++;
                zcglCustomerQueryWrapper.lambda().eq(ZcglCustomerEntity::getProject,zcglCustomerPagination.getProject());
                    }

			if(ObjectUtil.isNotEmpty(zcglCustomerPagination.getCustomerName())){
            zcglCustomerNum++;
            zcglCustomerQueryWrapper.lambda().like(ZcglCustomerEntity::getCustomerName,zcglCustomerPagination.getCustomerName());
                    }

        }
            if(zcglCustomerUserNum>0){
            List<String> zcglCustomerUserIdList = zcglCustomerUserService.list(zcglCustomerUserQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getParentid())).map(t->t.getParentid()).collect(Collectors.toList());
			long count = zcglCustomerUserService.count();
            if (count>0){
				intersectionList.add(zcglCustomerUserIdList);
            }
            AllIdList.addAll(zcglCustomerUserIdList);
            }
            total+=zcglCustomerUserNum;
            if(zcglCustomerBusinessNum>0){
            List<String> zcglCustomerBusinessIdList = zcglCustomerBusinessService.list(zcglCustomerBusinessQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getParentid())).map(t->t.getParentid()).collect(Collectors.toList());
			long count = zcglCustomerBusinessService.count();
            if (count>0){
				intersectionList.add(zcglCustomerBusinessIdList);
            }
            AllIdList.addAll(zcglCustomerBusinessIdList);
            }
            total+=zcglCustomerBusinessNum;
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         zcglCustomerQueryWrapper.lambda().in(ZcglCustomerEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            zcglCustomerQueryWrapper.lambda().and(t->t.in(ZcglCustomerEntity::getId, finalAllSuperIDlist));
		}

        //排序
        if(StringUtil.isEmpty(zcglCustomerPagination.getSidx())){
        zcglCustomerQueryWrapper.lambda().orderByDesc(ZcglCustomerEntity::getId);
        }else{
            try {
            	String sidx = zcglCustomerPagination.getSidx();
                ZcglCustomerEntity zcglCustomerEntity = new ZcglCustomerEntity();
				Field declaredField = zcglCustomerEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 zcglCustomerQueryWrapper="asc".equals(zcglCustomerPagination.getSort().toLowerCase())?zcglCustomerQueryWrapper.orderByAsc(value):zcglCustomerQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<ZcglCustomerEntity> page=new Page<>(zcglCustomerPagination.getCurrentPage(), zcglCustomerPagination.getPageSize());
                IPage<ZcglCustomerEntity> userIPage=this.page(page, zcglCustomerQueryWrapper);
                return zcglCustomerPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<ZcglCustomerEntity> list = new ArrayList();
                return zcglCustomerPagination.setData(list, list.size());
            }
        }else{
            return this.list(zcglCustomerQueryWrapper);
        }
    }


    @Override
    public ZcglCustomerEntity getInfo(String id){
        QueryWrapper<ZcglCustomerEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglCustomerEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglCustomerEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglCustomerEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ZcglCustomerEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法
	@Override
    public ZcglCustomerBusinessEntity getZcglCustomerBusiness(String id){
    	QueryWrapper<ZcglCustomerBusinessEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(ZcglCustomerBusinessEntity::getParentid, id);
        return zcglCustomerBusinessService.getOne(queryWrapper);
        }
	@Override
    public ZcglCustomerUserEntity getZcglCustomerUser(String id){
    	QueryWrapper<ZcglCustomerUserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(ZcglCustomerUserEntity::getParentid, id);
        return zcglCustomerUserService.getOne(queryWrapper);
        }



    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglCustomerForm form, int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		if (isUp){
			 id = form.getId();
		}
		if(ObjectUtil.isNotEmpty(form.getZcgl_customer_business())){
		}
		if(ObjectUtil.isNotEmpty(form.getZcgl_customer_user())){
		}
        if (total>0){
        return true;
        }
        return false ;
    }


}
